package com.dd.sample.utils;

import com.dd.processbutton.ProcessButton;

import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;

import java.security.SecureRandom;

public class ProgressGenerator {
    private final EventHandler eventHandler = new EventHandler(EventRunner.getMainEventRunner());

    private Runnable runnable;

    public interface OnCompleteListener {
        void onComplete();
    }

    private final OnCompleteListener mListener;
    private int mProgress;
    private SecureRandom random;

    public OnCompleteListener getListener() {
        return mListener;
    }

    public int getProgress() {
        return mProgress;
    }

    public void setProgress(int mProgress) {
        this.mProgress = mProgress;
    }

    public SecureRandom getRandom() {
        return random;
    }

    public ProgressGenerator(OnCompleteListener listener) {
        mListener = listener;
        try{
            random = SecureRandom.getInstance("SHA1PRNG");
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public void start(final ProcessButton button) {
        runnable = new Runnable() {
            @Override
            public void run() {
                mProgress += 10;
                button.setProgress(mProgress);
                if (mProgress < 100) {
                    eventHandler.postTask(this, generateDelay());
                } else {
                    mProgress = 0;
                    mListener.onComplete();
                }
            }
        };
        eventHandler.postTask(runnable, generateDelay());
    }

    public void stop() {
        eventHandler.removeTask(runnable);
    }

    private int generateDelay() {
        return random.nextInt(1000);
    }
}
